<template>
  <div class="page pb-70">
    <!-- 顶部栏 -->
    <van-nav-bar placeholder fixed :border="false">
      <template #left>
        <!-- Logo -->
        <img
          style="width: 80px; transform: translateY(5px)"
          src="../assets/img/logo.png"
        />
      </template>

      <template #right>
        <!-- 充值代币 -->
        <div class="click mr-10" @click="rechargeVisible = true">
          {{ $t('充值代币') }}
        </div>

        <!-- 国际化切换 -->
        <lang-comp></lang-comp>
      </template>
    </van-nav-bar>

    <!-- 公告 -->
    <div class="container">
      <van-notice-bar
        style="border-radius: 100px; overflow: hidden"
        mode="link"
      >
        <div class="fz-13">{{ $t('关于我们') }}</div>
      </van-notice-bar>
    </div>

    <!-- 内容 -->
    <div class="container pt-0">
      <pledge-comp v-if="tabIndex === 0"></pledge-comp>
      <market-comp v-else-if="tabIndex === 1"></market-comp>
      <index-comp
        @changeTab="(i) => (tabIndex = i)"
        v-else-if="tabIndex === 2"
      ></index-comp>
      <profit-comp v-else-if="tabIndex === 3"></profit-comp>
      <detail-comp v-else="tabIndex === 4"></detail-comp>
    </div>

    <!-- 底部栏 -->
    <ul class="footer flex bcl-black">
      <li
        class="flex flex-center click"
        style="width: 20%"
        v-for="(v, i) in tabs"
        :key="i"
        @click="changeTabIndex(i)"
      >
        <div>
          <div class="flex flex-center">
            <img
              :style="{ width: i === 2 ? '40px' : '18px', marginBottom: '2px' }"
              :src="i === tabIndex ? v.activeIcon : v.icon"
            />
          </div>
          <div :style="{ color: i === tabIndex ? '#745ee0' : 'white' }">
            {{ v.name }}
          </div>
        </div>
      </li>
    </ul>

    <!-- 充值代币 -->
    <van-popup
      style="background-color: transparent"
      v-model:show="rechargeVisible"
    >
      <div class="popup box" style="width: 85vw">
        <div class="fz-20 mb-15">{{ $t('充值') }}</div>

        <!-- 介绍 -->
        <div class="mb-15">{{ $t('充值介绍') }}</div>

        <!-- 充值金额 -->
        <div class="mb-15">
          <div class="mb-10">{{ $t('充值金额') }}</div>
          <van-field
            type="digit"
            :placeholder="$t('请输入充值金额')"
            v-model="amount"
          ></van-field>
        </div>

        <div class="flex flex-rc">
          <van-button type="primary" block round @click="recharge">
            {{ $t('充值') }}
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { computed, provide, ref } from 'vue'
import {
  showToast,
  showSuccess,
  showLoading,
  showError,
  toNumber,
  toBigNumber,
} from 'js/utils'

import langComp from 'comps/lang.vue'
import pledgeComp from 'comps/pledge.vue'
import marketComp from 'comps/market.vue'
import indexComp from 'comps/index.vue'
import profitComp from 'comps/profit.vue'
import detailComp from 'comps/detail.vue'

// 充值表单
const amount = ref('')
const rechargeVisible = ref(false)

// 类型
const tabs = ref([
  {
    name: $t('认购收益'),
    icon: getImage('pledge'),
    activeIcon: getImage('pledge_active'),
  },
  {
    name: $t('市场'),
    icon: getImage('market'),
    activeIcon: getImage('market_active'),
  },
  {
    icon: getImage('index'),
    activeIcon: getImage('index'),
  },
  {
    name: $t('收益'),
    icon: getImage('profit'),
    activeIcon: getImage('profit_active'),
  },
  {
    name: $t('明细'),
    icon: getImage('detail'),
    activeIcon: getImage('detail_active'),
  },
])
const tabIndex = ref(Number(localStorage.getItem('tabIndex') || '0'))

// 用户信息
const fromAddressRef = ref(fromAddress)
const fromAddressHideRef = ref(fromAddressHide)
const balance = ref(0)
const pandax = ref(0)
const usdtExchange = ref(0)
provide(
  'balance',
  computed(() => balance.value)
)
provide(
  'pandax',
  computed(() => pandax.value)
)
provide(
  'usdtExchange',
  computed(() => usdtExchange.value)
)

initApp()

// 初始化App
async function initApp() {
  balance.value = await getAccountBalance()
  pandax.value = await getPandaxBalance()
  usdtExchange.value = await getUsdtExchangeBalance()
}

// 获取账户余额
function getAccountBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取账户余额')
      const balance = await usdtContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取账户余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取账户余额失败')
      console.error('获取账户余额失败')
      console.error(err)
    }
  })
}

// 获取Pandax余额
function getPandaxBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取Pandax余额')
      const balance = await pandaxContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取pandax余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取pandax余额失败')
      console.error('获取pandax余额失败')
      console.error(err)
    }
  })
}

// 获取兑换Usdt余额
function getUsdtExchangeBalance() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取兑换Usdt余额')
      const balance = await usdtExchangeContract.context.methods
        .balanceOf(fromAddress)
        .call()
      const balanceInBigNumber = toNumber(balance)
      console.log(`获取兑换Usdt余额成功：${balanceInBigNumber}`)
      resolve(balanceInBigNumber)
    } catch (err) {
      showError('获取兑换Usdt余额失败')
      console.error('获取兑换Usdt余额失败')
      console.error(err)
    }
  })
}

// 充值代币
async function recharge() {
  if (!amount.value) {
    return showToast($t('请输入充值金额'))
  }

  if (Number(usdtExchange.value) < Number(amount.value)) {
    return showToast($t('Usdt余额不足'))
  }

  const loading = showLoading()

  try {
    // 判断兑换Usdt授权给兑换Coin的额度是否足够，不够就先授权额度
    const authorizedBalanceByUsdt = await getAuthorizedBalanceByUsdt()

    if (authorizedBalanceByUsdt <= 0) {
      // 需要授权额度
      await authorizeBalanceByUsdt()
    } else if (authorizedBalanceByUsdt < Number(amount.value)) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByUsdt()
    }

    // 下单
    await investAmount()
    loading?.close()
  } catch (err) {
    console.error(err)
    loading?.close()
  }
}

// 下单
function investAmount() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log(`充值金额：${amount.value}`)
      const res = await coinExchangeContract.context.methods
        .swap(toBigNumber(amount.value))
        .send({
          from: fromAddress,
        })
      amount.value = ''
      initApp()
      showSuccess($t('充值成功'))
      console.log('充值成功')
      console.log(res)
      resolve(res)
    } catch (err) {
      amount.value = ''
      showError($t('充值失败'))
      console.error('充值失败')
      console.error(err)
      reject(err)
    }
  })
}

// 兑换Usdt授权兑换Coin额度
function authorizeBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(100000) // 授权 100000 Usdt额度
      const res = await usdtExchangeContract.context.methods
        .approve(coinExchangeContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权余额成功'))
      console.log(`授权兑换Usdt余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError($t('授权余额失败'))
      console.error('授权兑换Usdt余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取兑换Usdt授权给兑换Coin的额度
function getAuthorizedBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await usdtExchangeContract.context.methods
        .allowance(fromAddress, coinExchangeContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取兑换Usdt授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取授权余额失败'))
      console.error('获取兑换Usdt授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取图片
function getImage(name) {
  return new URL(`../assets/img/icon/${name}.png`, import.meta.url).href
}

function changeTabIndex(i) {
  tabIndex.value = i
  localStorage.setItem('tabIndex', i)
}
</script>

<style lang="scss">
.footer {
  text-align: center;
  border-top: 1px solid #2d3245;
  padding: 10px 0;
}
</style>
